<?php
/**
 * Created by JetBrains PhpStorm.
 * User: Raul
 * Date: 5/29/13
 * Time: 4:13 PM
 * To change this template use File | Settings | File Templates.
 */
define('BASEPATH', true);
define('URL', 'http://219.239.223.9:8082/ip/verify');
define('ENV', 'master');
define('TIME', 3600);
define('STATUS', 0);
define('STATUS_DELE', -5);
define('FLAG', 'yes');
define('TIME_SLOT', 120);
define('LIMIT', 200);
date_default_timezone_set('Asia/Shanghai');
$projectPath = dirname(dirname(__FILE__));
require_once($projectPath . '/application/config/database.php');

$db = new mysqli($db[ENV]['hostname'], $db[ENV]['username'], $db[ENV]['password'], $db[ENV]['database']);

$ips = getIPs();

if(!$ips) {
    exit("No ip to verify.\n");
}

foreach($ips as $ip) {
    $result = getContent($ip['ip'], $ip['port']);
    $update = array(
        'id'        => $ip['id'],
        'status'    => 1,
        'vtime'     => time()
    );
    if($result != FLAG) {
        $update['status'] = $ip['status'] - 1;
    }
    updateIP($update);
    $str = "IP: ".$ip['ip']."\tPort: ".$ip['port']."\tStatus: ".$update['status']."\tVerify Time: ".$update['vtime']."\n";
    echo $str;
}

delIPs();
$db->close();

function getIPs() {
    global $db;
    $sql = "SELECT * FROM proxy WHERE vtime = 0 AND ctime < ".(time() - TIME_SLOT)." ORDER BY ctime DESC";
    $query = $db->query($sql);
    if(!$query->num_rows) {
        return false;
    }
    $result = array();
    while($row = $query->fetch_array(MYSQLI_ASSOC)) {
        $result[] = $row;
    }
    return $result;
}

function updateIP($update) {
    global $db;
    $sql = "UPDATE proxy SET status = ".$update['status'].", vtime = ".$update['vtime']." WHERE id = ".$update['id'];
    $db->query($sql);
}

function getContent($ip, $port) {
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, URL);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION,1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_TIMEOUT, 2);
    curl_setopt($ch, CURLOPT_PROXY, $ip . ':' . $port);

    $result = curl_exec($ch);
    curl_close($ch);
    return $result;
}

function delIPs() {
    global $db;
    $sql = "DELETE FROM mobility_ip WHERE status = ".STATUS." AND ctime < ".(time() - TIME * 24);
    $query = $db->query($sql);

    $sql = "DELETE FROM proxy WHERE status < ".STATUS_DELE;
    $query = $db->query($sql);

}